<?php 

namespace Cli\Event;

use Think\Log;
use Api\Event\CacheEvent;
use Api\Manage\SysNoticeManage;
// +----------------------------------------------------------------------
// | 文件 TestCronEvent.class.php
// +----------------------------------------------------------------------
// | 说明 测试CRON
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Author: 谢赤心 Legend. <xcx_legender@qq.com>
// +----------------------------------------------------------------------

class VideoplayCronEvent extends CronEvent
{

    static $RedisInst = null;
    static $RedisQueueKey = "IMBA.QUEUE.VIDEOPLAY";

    static protected function getRedis()
    {
        if (!self::$RedisInst){
            self::$RedisInst = CacheEvent::instance(8);
        }
        self::$RedisInst;
    }
 
    public function run()
    {
        // 每次处理10000W个数据
        self::getRedis();
        if (!self::$RedisInst){
            echo 'redis err';
            Log::record("[swoole] - [videoplay]: warning: redis connect err",'WARNING');
            Log::save();
            return;
        }
        $statisEvent = event('Statis');
        $videService = service('Video');
        $videoEvent  = event('Video');
        for ($i=0; $i < 10000; $i++) { 
            $data = self::$RedisInst->lpop(self::$RedisQueueKey);
            print_r($data);
            if (!$data){ // 没有数据就停止
                break;
            }
            $data = json_decode($data, true);
            if (!$data){
                // 如果解析失败就丢弃
                continue;
            }
            extract($data);
            $statisEvent->operStatisVideo($video_id, 0, 'play', $step, $extend);
            $save = [
                'id'   => (int)$video_id,
                'play' => ['inc', $step],
            ];
            $videService->save($save);
            $video = $videoEvent->detail($video_id);
            if ($video['type'] == 0){
                $statisEvent->inRank($video_id, $step);
            } 
            SysNoticeManage::afterPlay($video, $user, $step);
            echo $video_id,':ok\r\n';
        }


    }
}